Implement Trie

Implement a trie with insert, search, and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.

Solution:

  1. class TrieNode {
  2. char c;
  3. boolean isLeaf;
  4. Map<Character, TrieNode> children = new HashMap<>();
  5. public TrieNode() {}
  6. public TrieNode(char c) {
  7. this.c = c;
  8. }
  9. }
  10. public class Trie {
  11. private TrieNode root;
  12. public Trie() {
  13. root = new TrieNode();
  14. }
  15. // Inserts a word into the trie.
  16. public void insert(String word) {
  17. Map<Character, TrieNode> children = root.children;
  18. for (int i = 0; i < word.length(); i++) {
  19. char c = word.charAt(i);
  20. if (!children.containsKey(c)) {
  21. children.put(c, new TrieNode(c));
  22. }
  23. if (i == word.length() - 1) {
  24. children.get(c).isLeaf = true;
  25. }
  26. children = children.get(c).children;
  27. }
  28. }
  29. // Returns if the word is in the trie.
  30. public boolean search(String word) {
  31. TrieNode node = getLastTrieNode(word);
  32. return node != null && node.isLeaf;
  33. }
  34. // Returns if there is any word in the trie
  35. // that starts with the given prefix.
  36. public boolean startsWith(String prefix) {
  37. TrieNode node = getLastTrieNode(prefix);
  38. return node != null;
  39. }
  40. private TrieNode getLastTrieNode(String word) {
  41. Map<Character, TrieNode> children = root.children;
  42. for (int i = 0; i < word.length(); i++) {
  43. char c = word.charAt(i);
  44. if (!children.containsKey(c)) {
  45. break;
  46. }
  47. if (i == word.length() - 1)
  48. return children.get(c);
  49. children = children.get(c).children;
  50. }
  51. return null;
  52. }
  53. }
  54. // Your Trie object will be instantiated and called as such:
  55. // Trie trie = new Trie();
  56. // trie.insert("somestring");
  57. // trie.search("key");